package ${initProjectVo.packageNameValue}.core.interceptor;

import ${initProjectVo.packageNameValue}.common.jwt.JWTUtils;
import ${initProjectVo.packageNameValue}.core.wrapper.HeaderHttpServletRequestWrapper;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Faye.Wang
* @version 1.0
* @date 2020/11/3 12:00
* @Description
*/
public class HeaderInterceptor implements Filter {


    private String excludes;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludes =  filterConfig.getInitParameter("excludes");
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    
        if(handleExcludeURL(httpRequest, httpResponse)){
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    String accessToken = httpRequest.getHeader(JWTUtils.AUTH_HEADER_KEY);
        String sessionId = JWTUtils.getTokenObjectValue(accessToken,"sessionId");

        HeaderHttpServletRequestWrapper requestWrapper = new HeaderHttpServletRequestWrapper(httpRequest);
        requestWrapper.setSessionId(sessionId);
        filterChain.doFilter(requestWrapper,httpResponse);
    }
    
    @Override
    public void destroy() {
    
    }
    
    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
    
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
    
        String url = request.getServletPath();
        for (String pattern : excludes.split(",")) {
        Pattern p = Pattern.compile("^" + pattern);
        Matcher m = p.matcher(url);
        if (m.find()) {
            return true;
        }
    }
    
        return false;
    }

}
